package com.dy.yunying.biz.datasource;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;

import java.util.Date;
import java.util.Objects;

/**
 * @author zhuxm
 * @date 2021/01/08
 */
public class MetaObjectHandlerConfig implements MetaObjectHandler {

	private static final String CREATE_TIME = "createtime";
	private static final String CREATE_TIME2 = "createTime";

	private static final String UPDATE_TIME = "updatetime";
	private static final String UPDATE_TIME2 = "updateTime";

	@Override
	public void insertFill(MetaObject metaObject) {
		Date date = new Date();
		if (metaObject.hasSetter(CREATE_TIME)) {
			Object createtime = getFieldValByName(CREATE_TIME, metaObject);
			if (Objects.nonNull(createtime)) {
				this.setFieldValByName(CREATE_TIME, createtime, metaObject);
			} else {
				this.setFieldValByName(CREATE_TIME, date, metaObject);
			}
		}

		if (metaObject.hasSetter(CREATE_TIME2)) {
			Object createTime = getFieldValByName(CREATE_TIME2, metaObject);
			if (Objects.nonNull(createTime)) {
				this.setFieldValByName(CREATE_TIME2, createTime, metaObject);
			} else {
				this.setFieldValByName(CREATE_TIME2, date, metaObject);
			}
		}
		if (metaObject.hasSetter(UPDATE_TIME)) {
			Object updatetime = getFieldValByName(UPDATE_TIME, metaObject);
			if (Objects.nonNull(updatetime)) {
				this.setFieldValByName(UPDATE_TIME, updatetime, metaObject);
			} else {
				this.setFieldValByName(UPDATE_TIME, date, metaObject);
			}
		}

		if (metaObject.hasSetter(UPDATE_TIME2)) {
			Object updateTime = getFieldValByName(UPDATE_TIME2, metaObject);
			if (Objects.nonNull(updateTime)) {
				this.setFieldValByName(UPDATE_TIME2, updateTime, metaObject);
			} else {
				this.setFieldValByName(UPDATE_TIME2, date, metaObject);
			}
		}

	}

	@Override
	public void updateFill(MetaObject metaObject) {

		Date date = new Date();
		if (metaObject.hasSetter(UPDATE_TIME)) {
			Object updatetime = getFieldValByName(UPDATE_TIME, metaObject);
			if (Objects.nonNull(updatetime)) {
				this.setFieldValByName(UPDATE_TIME, updatetime, metaObject);
			} else {
				this.setFieldValByName(UPDATE_TIME, date, metaObject);
			}
		}

		if (metaObject.hasSetter(UPDATE_TIME2)) {
			Object updateTime = getFieldValByName(UPDATE_TIME2, metaObject);
			if (Objects.nonNull(updateTime)) {
				this.setFieldValByName(UPDATE_TIME2, updateTime, metaObject);
			} else {
				this.setFieldValByName(UPDATE_TIME2, date, metaObject);
			}
		}

	}
}
